Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

348
Vistas
Why does 11010100 << 1 equal 110101000, not 10101000?

Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.

int a = Integer.parseInt("11010100", 2) << 1;

I try to do this:

int a = (byte)(Integer.parseInt("11010100", 2) << 1);

But if the output value is greater than 128, everything goes into minus, which is logical. How can I make that number of bits does not change?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

If you want to set to 0 all bits higher than the bottom 8 bits, you can use bit-wise AND:

int a = (Integer.parseInt("11010100", 2) << 1) & 0xff;
System.out.println (Integer.toString(a,2));

Output:

10101000
over 4 years ago · Santiago Trujillo Denunciar

0

Let's take it one step at a time.

  1. Integer.parseInt("11010100", 2) - this is the int value 212. This is, by the way, needless; you can just write: 0b11010100.

  2. 0b11010100 << 1 is the same as 0b110101000, and is 424.

  3. You then cast it to a byte: (byte)(0b11010100 << 1). The bits beyond the first 8 all get lopped off, which leaves 0b10101000, which is -88. Minus, yes, because in java bytes are signed.

  4. You then silently cast this -88 back up to int, as you assign it to an int value. It remains -88, which means all the top bits are all 1s.

Hence, the final value is -88.

If you want to see 168 instead (which is the exact same bits, but shown unsigned instead of signed), the usual trick is to use & 0xFF, which sets all bits except the first 8 to 0, thus guaranteeing a positive number:

byte b = (byte) (0b11010100 << 1);
System.out.println(b); // -88. It is not possible to print 168 when printing a byte.
int asUnsigned = b & 0xFF;
System.out.println(asUnsigned); // 168.

// or in one go:

System.out.println(((byte) (0b11010100 << 1)) & 0xFF); // 168

over 4 years ago · Santiago Trujillo Denunciar

0

Try something like this:

int anInt = Integer.parseInt("11010100", 2) << 1;
int asUnsignedInt= Byte.toUnsignedInt((byte) anInt);

toUnsignedInt has been introduced in Java SE 8.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda